package com.hj.interceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hj.dao.MenuMapper;
import com.hj.dao.RoleMenuMapper;
import com.hj.dao.StuRoleMapper;
import com.hj.pojo.Menu;
import com.hj.pojo.MenuExample;
import com.hj.pojo.RoleMenu;
import com.hj.pojo.RoleMenuExample;
import com.hj.pojo.StuRole;
import com.hj.pojo.StuRoleExample;
import com.hj.pojo.StuRoleExample.Criteria;
import com.hj.pojo.Student;
import com.hj.vo.Result;

//@Component
public class LoginInterceptor implements HandlerInterceptor {
	
	ObjectMapper om = new ObjectMapper();
	@Autowired
	StuRoleMapper stuRoleMapper;
	@Autowired
	RoleMenuMapper roleMenuMapper;
	@Autowired
	MenuMapper menuMapper;
	

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		HttpSession session = request.getSession();
		response.setCharacterEncoding("utf-8");
		
		Object uid = session.getAttribute("sessionUid");
		
		if (uid == null) {
			Result result = new Result();
	        result.setCode(201);
	        result.setMsg("请登录");
			response.getWriter().append(om.writeValueAsString(result));
			return false;
		}
		
		List<Menu> menuList = menuMapper.selectMenuByUid(uid.toString());
		
		// 获取当前访问的路径的
		String servletPath = request.getServletPath();
		
		boolean flag = false;
		// 比对是否存在角色权限列表中
		for (Menu menu : menuList) {
			if (servletPath.equals(menu.getPath())) {
				flag = true;
				break;
			}
		}
		
		if (!flag) {
			Result result = new Result();
			result.setCode(202);
			result.setMsg("无权限1");
			response.getWriter().append(om.writeValueAsString(result));
			return false;
		}
		
		return true;
	}
	
}
